package com.yixia.framework.web.service;


import com.yixia.common.constant.CacheConstants;
import com.yixia.common.constant.Constants;
import com.yixia.common.constant.UserConstants;
import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.core.domain.model.LoginBody;
import com.yixia.common.core.domain.model.LoginUser;
import com.yixia.common.core.redis.RedisCache;
import com.yixia.common.exception.ServiceException;
import com.yixia.common.exception.user.*;
import com.yixia.common.utils.DateUtils;
import com.yixia.common.utils.MessageUtils;
import com.yixia.common.utils.StringUtils;
import com.yixia.common.utils.ip.IpUtils;
import com.yixia.framework.manager.AsyncManager;
import com.yixia.framework.manager.factory.AsyncFactory;
import com.yixia.framework.security.context.AuthenticationContextHolder;
import com.yixia.system.service.system.SysConfigService;
import com.yixia.system.service.system.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.TimerTask;


@Service
public class SysLoginService {

    /*获取认证管理器*/
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    /**
     * 登录验证
     * 1.先构建UsernamePasswordAuthenticationToken对象，将用户名和密码装入
     * 2.
     * @param loginBody
     * @return
     */
    public String login(LoginBody loginBody) {

        /*1、先验证验证码是否正确*/
        validateCaptcha(loginBody.getUsername(), loginBody.getCode(), loginBody.getUuid());
        /*2、再次对登录的loginBody进行验证*/
        loginPreCheck(loginBody.getUsername(), loginBody.getPassword());
        /*AuthenticationManager authenticate来进行认证*/
        Authentication authenticate = null;
        try {
            //1.认证没通过给出提示
            /*UsernamePasswordAuthenticationToken是Authentication接口的实现类*/
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);//将认证信息存储到Holder中
            /*authenticationManager.authenticate会调用MyUserDetailsServiceImpl也就是UserDetailsService的实现类来查数据库进行验证*/
            authenticate = authenticationManager.authenticate(authenticationToken);/*AuthenticationManager的认证方法*/

        }catch (Exception e){
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }

        }finally
        {
            AuthenticationContextHolder.clearContext();//失败就清除认证信息
        }

        /*authenticate的结果是null表示认证不通过，否则认证通过*/

        /*登录成功的异步请求*/
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        //2.认证通过使用userid来生成一个jwt，并且将jwt存入AjaxResult进行返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        //存入记录登录次数信息
        recordLoginInfo(loginUser.getUserId());

        /*生成token，并返回给前端*/
        return tokenService.createToken(loginUser);
    }


    /**
     * 验证码校验
     * @param username
     * @param code
     * @param uuid
     */
    public void validateCaptcha(String username, String code, String uuid){
        /*1.先判断是否有验证码*/
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        //2. 有，对其进行验证
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            //2.1 从redis中获取信息
            String captcha = redisCache.getCacheObject(verifyKey);
            //2.2 从redis中删除缓存
            redisCache.deleteObject(verifyKey);
            //2.3 redis中没有获取到数据
            if(captcha == null){
                //通过异步任务来记录一下用户操作
                String message = MessageUtils.message("user.jcaptcha.expire");
                TimerTask timerTask = AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, message);
                AsyncManager.me().execute(timerTask);
                throw new CaptchaExpireException();
            }else if (!code.equalsIgnoreCase(captcha)){
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
        //3. 没有就不验证
    }


    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password){
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        String ipAddr = IpUtils.getIpAddr();
        sysUser.setLoginIp(ipAddr);
        sysUser.setLoginDate(DateUtils.getNowDate());/*将当前时间装入*/
        userService.updateUserProfile(sysUser);/*更新数据库信息*/
    }



}
